﻿using Newtonsoft.Json;

namespace MicroCloud.Entity
{
    /// <summary>
    /// 实体属性构建器功能扩展
    /// </summary>
    public static class PropertyBuilderExtensions
    {
        /// <summary>
        /// 存储值JSON转换
        /// </summary>
        /// <typeparam name="T">属性类型</typeparam>
        /// <param name="propertyBuilder">属性构建器</param>
        /// <returns></returns>
        public static PropertyBuilder<T> HasJsonConversion<T>(this PropertyBuilder<T> propertyBuilder)
        {
            ValueConverter<T, string> converter = new(
                model => JsonConvert.SerializeObject(model),
                provider => JsonConvert.DeserializeObject<T>(provider)
            );

            ValueComparer<T> comparer = new(
                (l, r) => JsonConvert.SerializeObject(l) == JsonConvert.SerializeObject(r),
                v => v == null ? 0 : JsonConvert.SerializeObject(v).GetHashCode(),
                v => JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(v))
            );

            //new ValueComparer<string[]>(
            //    (c1, c2) => c1.SequenceEqual(c2),
            //    c => c.Aggregate(0, (a, v) => HashCode.Combine(a, v.GetHashCode())),
            //    c => c.ToArray())

            propertyBuilder.HasConversion(converter);
            propertyBuilder.Metadata.SetValueConverter(converter);
            propertyBuilder.Metadata.SetValueComparer(comparer);
            //propertyBuilder.HasColumnType("jsonb");

            return propertyBuilder;
        }
      
        /// <summary>
        /// 存储值JSON转换
        /// </summary>
        /// <typeparam name="T">属性类型</typeparam>
        /// <param name="propertyBuilder">属性构建器</param>
        /// <returns></returns>
        public static PropertyBuilder HasJsonConversion<T>(this PropertyBuilder propertyBuilder)
        {
            ValueConverter<T, string> converter = new(
                model => JsonConvert.SerializeObject(model),
                provider => JsonConvert.DeserializeObject<T>(provider)
            );

            ValueComparer<T> comparer = new(
                (l, r) => JsonConvert.SerializeObject(l) == JsonConvert.SerializeObject(r),
                v => v == null ? 0 : JsonConvert.SerializeObject(v).GetHashCode(),
                v => JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(v))
            );

            propertyBuilder.HasConversion(converter);
            //propertyBuilder.Metadata.SetValueConverter(converter);
            propertyBuilder.Metadata.SetValueComparer(comparer);
            //propertyBuilder.HasColumnType("jsonb");

            return propertyBuilder;
        }

    }
}